package com.example.demo.redis;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.concurrent.CountDownLatch;

/**
 * 加锁解锁测试
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class RedisLockServiceTest1 {

    @Autowired
    private RedisLockService redisLockService;

//    @Autowired
    private StockService stockService;

    @Autowired
    private OtherService otherService;

    @Test
    public void testLock() {
//        boolean res = redisLockService.lock("a", "123", 100L);
        boolean res = redisLockService.lock("a", "123");
        System.out.println(res);
    }

    @Test
    public void testUnlock() {
        boolean res = redisLockService.unlock("a", "123");
        System.out.println(res);
    }

    /**
     * 注解测试
     */
    @Test
    public void testAnnotation() {
        int size = 1000;
        //使用2个倒计时来实现所有线程都创建完毕后同一时间进行减库存操作
        CountDownLatch startLatch = new CountDownLatch(size);
        CountDownLatch endLatch = new CountDownLatch(size);
        for (int i = 0; i < size; i++) {
            Thread t = new StockThread(stockService, startLatch, endLatch);
            t.start();
            startLatch.countDown();
        }
        try {
            endLatch.await();
            System.out.println("剩余库存" + stockService.getStock());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 注解SpringEl测试
     */
    @Test
    public void testSpringEL() {
        Student student = new Student();
        student.setName("小明");
        Teacher teacher = new Teacher();
        teacher.setName("王老师");
        otherService.test(student, teacher);
    }

    @Test
    public void test() {
        try {
            if (redisLockService.lock("a", "123")) {
                System.out.println("锁成功");
                try {
                    Thread.sleep(1000L * 61);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        } finally {
            redisLockService.unlock("a", "123");
        }
        System.out.println("解锁");
        try {
            Thread.sleep(50000L);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}